package server;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import communication.server.*;
import exception.BadArgumentValueException;

public class GamePool {
	private GMHandle gmHandle;
	private HashMap<String, ClientHandle> waitPool = new HashMap<String, ClientHandle>(); //ArrayList
	//private ArrayList<Play> plays;	
	private HashMap<String, Play> plays = new HashMap<String, Play>();
	private int playersCountToStartGame;
	private int playId;

	public GamePool(GMHandle gmHandle, int playersCountToStartGame) {
		this.gmHandle = gmHandle;
		this.playersCountToStartGame = playersCountToStartGame;
		playId = 0;
	}
	
	public synchronized void addClient(ClientHandle ch) throws IOException {
		waitPool.put(ch.getNick(), ch);
		//if(waitPool.size() >= playersCountToStartGame)
		//	startPlay();
	}
	
	//public synchronized  boolean removeClient(ClientHandle ch) {
		//return waitPool.//waitPool.remove(ch);
	//}
	
	public synchronized GMHandle getGMHandle() {
		return gmHandle;
	}
	
	public synchronized HashMap<String, Play> getPlays() {
		return plays;
	}
		
	public int getNumberOfWaitingPlayers() {
		return waitPool.size();
	}
	
	public int getMinNumberOfPlayersToStartGame() {
		return playersCountToStartGame;
	}
	
	public Set<String> getWaitingPlayers() {
		return waitPool.keySet();
	}
	
	//rozpoczyna gr� dla playersCountToStartGame o wybranych nickach
	public void startPlay(String[] players) throws BadArgumentValueException, IOException {
		if(players.length != playersCountToStartGame)
			throw new BadArgumentValueException("startPlay() wywo�ane z list� graczy o d�ugo�ci r�nej od wymaganej.");
		Play play = new Play(playersCountToStartGame, playId++, gmHandle);
		for(int i = 0; i < players.length; ++i) {
			play.addPlayer(waitPool.get(players[i]));
			waitPool.get(players[i]).setGameId("" + playId);
			waitPool.remove(players[i]); 
		}
		plays.put("" + playId, play);
		gmHandle.startGame("" + playId, play.getPlayers());
	}

	//rozpoczyna gr� dla playersCountToStartGame graczy z pocz�tku listy
	public void startPlay() throws IOException {
		int i = 0;
		Play play = new Play(playersCountToStartGame, playId++, gmHandle);
		for(Iterator<ClientHandle> it = waitPool.values().iterator(); it.hasNext(); ) { //newValueIterator();
			ClientHandle client = it.next();
			if(i == this.playersCountToStartGame)
				break;
			++i;
			client.setGameId("" + playId);
			play.addPlayer(client);
			it.remove();
		}
		plays.put("" + playId, play);
		gmHandle.startGame("" + playId, play.getPlayers());
	}
	
}
